package com.woniuxy.hospital.controller;


import com.woniuxy.hospital.entity.HplAdmin;
import com.woniuxy.hospital.hplutils.ResponseEntity;
import com.woniuxy.hospital.hplutils.ResponseState;
import com.woniuxy.hospital.shiro.Audience;
import com.woniuxy.hospital.shiro.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2021-08-12
 */
@RestController
@RequestMapping("/hpl-admin")
public class HplAdminController {
    @Autowired
    private Audience audience;

    //登录
    @PostMapping("login")
    public ResponseEntity<?> login(@RequestBody HplAdmin admin, HttpServletResponse response){

        UsernamePasswordToken token = new UsernamePasswordToken(admin.getAccount(),admin.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try{
            subject.login(token);
            //成功
            //产生JWT
            //session.setAttribute("admin",admin1);
            HplAdmin admin2 = (HplAdmin)subject.getSession().getAttribute("admin");
            String jwt = JwtUtil.createJWT(admin2.getId(),admin2.getAccount(),audience);
            response.setHeader("jwt",jwt);
            return ResponseEntity.SUCCESS;
        }catch (UnknownAccountException e){
            //账号不存在
            return new ResponseEntity<Void>(ResponseState.FAIL, "账号不存在");
        }catch (IncorrectCredentialsException e){
            //密码错误
            return new ResponseEntity<Void>(ResponseState.FAIL, "密码错误");
        }
    }

}

